﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Security;
using BackEnd.Models;
using BackEnd.Common;
using BusinessLayer.RegInfo;
using BusinessLayer.RegInfo.Entities;
using BusinessLayer.RegInfo.Models;

namespace BackEnd.Controllers
{
    
    public class AdminUserController : Controller
    {
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        //
        // POST: /Account/Login
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                var userBL = new AdminUserBL();
                if (userBL.ValidateUser(model.UserName, CommandLib.Encrypt.EncodeToSHA512(model.Password)))
                {

                    Session[Common.Constants.SessionKeys.UserInfo] = model.UserName;
                    var lstActions = new AdminActionBL().GetAdminActionsByUserName(model.UserName);
                    string actions = String.Empty;
                    foreach (var ac in lstActions)
                    {
                        actions += ac.Code + ";";
                    }
                    if (!String.IsNullOrEmpty(actions))
                    {
                        Session[Common.Constants.SessionKeys.PermissionActions] = actions;

                    }
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);                    
                    return RedirectToLocal(returnUrl);

                }
            }

            // If we got this far, something failed, redisplay form
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
            return View(model);
        }

        //
        // POST: /Account/LogOff

        //[HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            Session.Clear();

            return RedirectToAction("LogIn", "AdminUser");
        }

        //
        // GET: /Account/Create
        [CustomAuthorize(Action = Common.Constants.AdminActions.CreateAdminUser)]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Account/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        [CustomAuthorize(Action = Common.Constants.AdminActions.CreateAdminUser)]
        public ActionResult Create(UserCreateModel model)
        {
            if (ModelState.IsValid)
            {
                
                    // Attempt to create the user
                    var userBL = new AdminUserBL();
                    var user = new AdminUser();
                    user.FirstName = model.FirstName;
                    user.LastName = model.LastName;
                    user.Password = model.Password;
                    user.Status = Common.Constants.Status.ACTIVE;//default status when creating is ACTIVE.
                    user.UserName = model.UserName;
                    string result = String.Empty;
                    if (userBL.GetByUserName(user.UserName) != null)
                    {
                        result = "User name already exists. Please enter a different user name.";
                    }
                    else
                    {
                        user.Password = CommandLib.Encrypt.EncodeToSHA512(user.Password);
                        if (userBL.CreateAdminUser(user) > 0)
                        {
                            return RedirectToAction("Index", "AdminUser");
                        }
                        else
                        {
                            result = "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
                        }
                    }
                    
                
                    ModelState.AddModelError("", result);
                
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        [CustomAuthorize(Action = Common.Constants.AdminActions.UpdateAdminMenu)]
        public ActionResult ChangePassword()
        {

            return View();
        }
       
        [HttpPost]
        [CustomAuthorize(Action = Common.Constants.AdminActions.UpdateAdminMenu)]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var userBL = new AdminUserBL();
                if (userBL.ChangePasswordByUserName(Session[Constants.SessionKeys.UserInfo].ToString(),CommandLib.Encrypt.EncodeToSHA512(model.OldPassword), CommandLib.Encrypt.EncodeToSHA512(model.NewPassword)))
                {                    
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            return View(model);
        }

        [CustomAuthorize(Action = Common.Constants.AdminActions.ResetPasswordAdminUser)]
        public ActionResult ResetPassword()
        {
            return View();
        }
        
        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.ResetPasswordAdminUser)]
        public ActionResult ResetPassword(ResetPasswordModel model)
        {
            if (ModelState.IsValid)
            {
                var userBL = new AdminUserBL();
                if (userBL.ResetPasswordByUserName(model.UserName, CommandLib.Encrypt.EncodeToSHA512(model.NewPassword)))
                {                    
                    return RedirectToAction("ResetPasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            return View(model);
        }
        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            ViewBag.StatusMessage = "Change Password Success";
            return View("Password");
        }

        // **************************************
        // URL: /Account/ResetPasswordSuccess
        // **************************************
        public ActionResult ResetPasswordSuccess()
        {
            ViewBag.StatusMessage = "Reset Password Success";
            return View("Password");
        }

        // **************************************
        // URL: /Account/Index
        // *
        public ActionResult Index()
        {
            var subBL = new AdminUserBL();
            var lstAdminUsers = new List<AdminUserExtend>();
            lstAdminUsers.AddRange(subBL.GetAll());

            return View("Index", lstAdminUsers);
        }

        //
        // GET:/Account/Edit/id
        //[AcceptVerbs(HttpVerbs.Get)]
        [CustomAuthorize(Action = Constants.AdminActions.UpdateAdminUser)]
        public ActionResult Edit(int id)
        {
            var subBL = new AdminUserBL();
            var subs = subBL.GetByUserID(id);
            var subModel = new UpdateInfoModel();
            subModel.UserID = subs.UserID;
            subModel.UserName = subs.UserName;
            subModel.FirstName = subs.FirstName;
            subModel.LastName = subs.LastName;
            subModel.Status = subs.Status;

            var lstStatus = Common.Constants.Status.GetListStatus();
            ViewBag.ListStatus = lstStatus.ToArray();
            return View("Edit", subModel);
        }

        [HttpPost]
        [CustomAuthorize(Action = Constants.AdminActions.UpdateAdminUser)]
        public ActionResult Edit(UpdateInfoModel model)
        {
            if (ModelState.IsValid)
            {
                var subsBL = new AdminUserBL();
                var check = subsBL.GetByUserID(model.UserID);
                if (check != null)
                {
                    var subs = new AdminUser();
                    subs.UserID = model.UserID;
                    subs.UserName = model.UserName;
                    subs.FirstName = model.FirstName;
                    subs.LastName = model.LastName;
                    subs.Status = model.Status;

                    int result = subsBL.UpdateAdminUser(subs);
                    if (result > 0)
                    {                        
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ViewData["ErrorMessage"] = "Has an error when executing update user info into database";
                    }
                }
                else
                {
                    ViewData["ErrorMessage"] = String.Format("This user - {0} not exists!", model.UserID);

                }

            }

            var lstStatus = Common.Constants.Status.GetListStatus();
            ViewData["ListStatus"] = lstStatus.ToArray();
            return View(model);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [CustomAuthorize(Action = Constants.AdminActions.DeleteAdminUser)]
        public ActionResult Delete(string id)
        {

            var userBL = new AdminUserBL();
            if (!String.IsNullOrEmpty(id))
            {
                List<string> lstOfUserIDs = new List<string>();
                foreach (string item in id.Split('_'))
                {
                    int temp = -1;
                    Int32.TryParse(item, out temp);
                    if (temp > 0)
                    {
                        lstOfUserIDs.Add(item);
                    }
                }
                int result = userBL.DeleteAdminUserByIds(lstOfUserIDs);
                if (result > 0)
                {                    
                    //return Json(1, JsonRequestBehavior.AllowGet);
                    ViewData["ErrorMessage"] = "Delete successful!";
                    return RedirectToAction("Index");
                }

            }
            //return Json(0, JsonRequestBehavior.AllowGet);
            ViewData["ErrorMessage"] = "Cannot delete selected items!";
            return RedirectToAction("Index");


        }

        // GET: /Account/Create
        [CustomAuthorize(Action = Constants.AdminActions.ViewAdminUsers)]
        public ActionResult Details(int id)
        {
            return View();
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }              
        #endregion
    }
}
